from flask import Blueprint, request, jsonify
from config import config as app_config
import logging

logger = logging.getLogger(__name__)

config_bp = Blueprint('config', __name__, url_prefix='/api/config')


@config_bp.route('', methods=['GET'])
def get_config():
    """获取系统配置"""
    try:
        config_data = {
            'mqtt': {
                'brokerHost': app_config.MQTT_BROKER_HOST,
                'brokerPort': app_config.MQTT_BROKER_PORT,
                'username': app_config.MQTT_USERNAME,
                'keepalive': app_config.MQTT_KEEPALIVE
            },
            'heartbeat': {
                'interval': app_config.HEARTBEAT_INTERVAL,
                'timeout': app_config.HEARTBEAT_TIMEOUT,
                'timeoutMultiplier': app_config.HEARTBEAT_TIMEOUT_MULTIPLIER,
                'timeoutOffset': app_config.HEARTBEAT_TIMEOUT_OFFSET
            }
        }
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': config_data
        })
    except Exception as e:
        logger.error(f"获取配置失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@config_bp.route('', methods=['PUT'])
def update_config():
    """更新系统配置（此接口仅用于演示，实际应通过环境变量配置）"""
    try:
        return jsonify({
            'code': 200,
            'message': '配置更新功能需要重启服务器，请修改环境变量后重启'
        })
    except Exception as e:
        logger.error(f"更新配置失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500

